const Service = require('egg').Service;
const jwt = require('jsonwebtoken')

const node_uid = require('node-uid')
const svgCaptcha = require('svg-captcha')

let codeText = '';
class UserService extends Service {
  // 验证码接口
  async authCode() {
    let captcha = svgCaptcha.create();
    // 将后端生成的验证码保存在后端命名空间；
    console.log('captcha', captcha.text)
    codeText = captcha.text;
    return { code: 0, msg: 'success', svg: captcha.data }
  }

  async login() {
    const { app, ctx } = this;
    const { username, password, authText } = ctx.request.body;
    console.log("authText: ", authText)
    console.log('this,codeText:', codeText.toLowerCase())
    if (authText === codeText.toLowerCase()) {
      const data = await app.mysql.get('users', {
        username: username,
        password: this.ctx.helper.getPassword(password)
      })
      if (data) {
        const token = jwt.sign({ ...data }, app.config.keys, { expiresIn: '24h' })
        return { code: 0, msg: '登陆成功', token, }
      } else {
        return { code: -1, msg: '登陆失败' }
      }
    } else {
      return {
        code: 0, msg: '验证码错误'
      }
    }
  }

  // 用户注册
  async register() {
    const { app, ctx } = this;
    const { username, password, userid } = ctx.request.body;

    const data = await app.mysql.get('users', { username })
    // select * from users where username=?

    if (data) {
      return { code: -1, msg: '账号已经存在' }
    } else {
      let stuid = node_uid(15)
      const data = await app.mysql.insert('users', {
        username,
        password: this.ctx.helper.getPassword(password),
        stuid,
        userid
      })
      if (data.affectedRows) {
        return { code: 0, msg: '注册成功', id: data.insertId }
      } else {
        return { code: -1, msg: '注册失败' }
      }
    }
  }

  // 查找用户
  async findUsers() {
    const data = await this.app.mysql.select('users')
    return { code: 0, msg: 'success', data }
  }

  // 删除用户
  async deleteUser() {
    const { id } = this.ctx.params;
    const { stuid } = this.ctx.request.body;
    const data = await this.app.mysql.delete('users', { id })
    if (data.affectedRows) {
      const deleteGrade = await this.app.mysql.delete('grade', { stuid })
      return { code: 0, msg: '删除成功', data: deleteGrade.affectedRows }
    } else {
      return { code: -1, msg: '删除失败', }
    }
  }


}

module.exports = UserService;